package com.eco
{
	//二维向量类
	public class MyVector2D
	{
		public var x :Number;
		public var y :Number;
		
		//赋予坐标值
		public function MyVector2D(x:Number,y:Number) 
		{
			this.x = x;
			this.y = y;
		}
		//转为字符输出
		public function toStr():String
		{
			var rx:Number = Math.round(this.x * 1000)/1000;
			var ry:Number = Math.round(this.y * 1000)/1000;
			return ("[" + rx + ", " + ry + "]");
		}
		//重设坐标值
		public function reset(x:Number,y:Number):void
		{
			this.x = x;
			this.y = y;
		}
		//克隆向量
		public function getClone():MyVector2D
		{
			return new MyVector2D(this.x,this.y);
		}
		//比较向量
		public function equals(v:MyVector2D):Boolean 
		{
			return (this.x == v.x && this.y == v.y);
		}
		//向量加法
		public function plus(v:MyVector2D):void
		{
			this.x += v.x;
			this.y += v.y;
		}
		//向量加法，返回值，不改变当前对象
		public function plusNew(v:MyVector2D):MyVector2D
		{
			return new MyVector2D(this.x + v.x,this.y + v.y);
		}
		//向量减法
		public function minus(v:MyVector2D):void
		{
			this.x -= v.x;
			this.y -= v.y;
		}
		//向量减法，返回值，不改变当前对象
		public function minusNew(v:MyVector2D):MyVector2D
		{
			return new MyVector2D(this.x - v.x,this.y - v.y);
		}
		//向量求逆
		public function negate():void
		{
			this.x = -this.x;
			this.y = -this.y;
		}
		//向量缩放
		public function scale(s:Number):void
		{
			this.x *= s;
			this.y *= s;
		}
		//向量缩放，返回值，不改变当前对象
		public function scaleNew(s:Number):MyVector2D
		{
			return new MyVector2D(this.x * s,this.y * s);
		}
		//向量长度,经典的勾股定理
		public function getLength():Number
		{
			return Math.sqrt(this.x * this.x + this.y * this.y);
		}
		//给定长度，修改vector对象的大小
		public function setLength(len:Number):void
		{
			var r:Number = this.getLength();
			if (r)
			{
				this.scale(len / r );
			} 
			else 
			{
				this.x = len;
			}
		}
		//向量角度
		public function getAngle():Number
		{
			return Math.atan2(this.y,this.x);
		}
		//保持长度，改造角度
		public function setAngle(angle:Number):void
		{
			var r:Number = this.getLength();
			this.x= r*cosD(angle);
			this.y= r*sinD(angle);
		}
		//点积
		public function dot(v:MyVector2D):Number
		{
			return (this.x * v.x + this.y * v.y);
		}
		//法向量，刚体碰撞的基础公式
		public function getNormal():MyVector2D
		{
			return new MyVector2D(- this.y,this.x);
		}
		//垂直验证
		public function isPerpTo(v:MyVector2D):Boolean
		{
			return (this.dot(v) == 0);
		}
		//向量的夹角
		public function angleBetween(v:MyVector2D):Number
		{
			var dp:Number =this.dot(v);
			var cosAngle:Number = dp / (this.getLength() * v.getLength());
			return acosD(cosAngle);
		}
		//改造SIN方法
		public function sinD(angle:Number):Number
		{
			return Math.sin(angle * Math.PI / 180);
		}
		//改造COS方法
		public function cosD(angle:Number):Number
		{
			return Math.cos(angle * Math.PI / 180);
		}
		//改造反余弦acos方法
		public function acosD(angle:Number):Number
		{
			return Math.acos(angle) * 180 / Math.PI;
		}
	}
}